package com.zgc.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zgc.common.BaseContext;
import com.zgc.common.R;

import com.zgc.entity.EmpRole;
import com.zgc.entity.Menu;
import com.zgc.entity.RoleMenu;
import com.zgc.service.EmpRoleService;

import com.zgc.service.MenuService;
import com.zgc.service.RoleMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@Slf4j
@RequestMapping("/menu")
public class MenuController {
    @Autowired
    private EmpRoleService empRoleService;
    @Autowired
    private RoleMenuService roleMenuService;
    @Autowired
    private MenuService menuService;
    //根据员工查角色，根据角色查菜单，根据菜单菜单组织树形结构
    @GetMapping("/list")
    public R list(){
        log.info("222222222222222222222");
        Long currentId = BaseContext.getCurrentId();
        LambdaQueryWrapper<EmpRole> lambdaQueryWrapper=new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(EmpRole::getEmpId, currentId.toString());
        EmpRole empRole= empRoleService.getOne(lambdaQueryWrapper);
        LambdaQueryWrapper<RoleMenu> lw=new LambdaQueryWrapper();
//没有配置角色，不能查询
        lw.eq(RoleMenu::getRoleId, empRole.getRoleId());
        List<RoleMenu> list=roleMenuService.list(lw);
        List<Menu> listMenu=new ArrayList<>();
        Set<String> set=new HashSet<>();
        for (int i=0;i<list.size();i++){
            RoleMenu roleMenu=list.get(i);
//所有子节点menu
            Menu menu= menuService.getById(roleMenu.getMenuId());
//获取所有的父id,获取父节点menu
            String parents=menu.getParentIds();
            if(null !=parents) {
                if (parents.contains(",")) {
                    String[] p = parents.split(",");
                    List<String> p1 = Arrays.asList(p);
                    set.addAll(p1);
                } else {
                    set.add(parents);
                }
            }
//添加到大集合中
            listMenu.add(menu);
        }
//父菜单填到大集合中
        Iterator it=set.iterator();
        while(it.hasNext()){
            String parentid= (String) it.next();
            Menu pmenu= menuService.getById(parentid);
            listMenu.add(pmenu);
        }
//集合排序放入顺序更美观
        Collections.sort(listMenu, new Comparator<Menu>() {
            @Override
            public int compare(Menu o1, Menu o2) {
                return (int) (o1.getShowOrder()-o2.getShowOrder());
            }
        });
//大集合做转换成树形结构
        return R.success(menuService.buildTreeIndex(listMenu));
    }
    //查询所有的菜单数据组成树形结构
    @GetMapping("/all")
    public R getMenus(){
        List<Menu> listall= menuService.list();
        return R.success(menuService.buildTreeSelect(listall));
    }
}